package gui.scheduler;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class ScheduleEditor extends JPanel {
	public ScheduleEditor() {
		SpringLayout layout = new SpringLayout();
		this.setLayout(layout);

		final MonthPanel panel = new MonthPanel();
		Calendar cal = new GregorianCalendar();
		panel.setMonth(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH));
		this.add(panel);
		layout.putConstraint(SpringLayout.WEST, panel, 3, SpringLayout.WEST, this);

		final JSpinner date = new JSpinner(new SpinnerDateModel());
		date.setEditor(new JSpinner.DateEditor(date,"MM/yy"));
		this.add(date);
		layout.putConstraint(SpringLayout.WEST, date, 3, SpringLayout.WEST, panel);
		layout.putConstraint(SpringLayout.NORTH, date,3, SpringLayout.NORTH, this);
		date.addChangeListener(new ChangeListener() {
			@Override
			public void stateChanged(ChangeEvent e) {
				Calendar cal = new GregorianCalendar();
				cal.setTime(((SpinnerDateModel)date.getModel()).getDate());
				panel.setMonth(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH));
			}
		});

		JButton update = new JButton("Update");
		this.add(update);
		layout.putConstraint(SpringLayout.EAST, update, 0, SpringLayout.EAST, panel);
		layout.putConstraint(SpringLayout.NORTH, update,3, SpringLayout.NORTH, this);

		final SpinnerDateModel model = new SpinnerDateModel();
		model.setCalendarField(Calendar.DAY_OF_MONTH);
		JSpinner generatedTo=new JSpinner(model);
		generatedTo.setEditor(new JSpinner.DateEditor(generatedTo, "MMMM dd, yyyy"));
		this.add(generatedTo);
		layout.putConstraint(SpringLayout.EAST, generatedTo, -5, SpringLayout.WEST, update);
		layout.putConstraint(SpringLayout.NORTH, generatedTo,6, SpringLayout.NORTH, this);

		JLabel label = new JLabel("Generate up to:");
		this.add(label);
		layout.putConstraint(SpringLayout.EAST, label,  -5, SpringLayout.WEST, generatedTo);
		layout.putConstraint(SpringLayout.NORTH, label,6, SpringLayout.NORTH, this);


		layout.putConstraint(SpringLayout.NORTH, panel,3, SpringLayout.SOUTH, update);
		layout.putConstraint(SpringLayout.SOUTH, panel,-3, SpringLayout.SOUTH, this);
		layout.putConstraint(SpringLayout.EAST, panel,-3, SpringLayout.EAST, this);

		update.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				Calendar cal = new GregorianCalendar();
				cal.setTime(model.getDate());
				cal.add(Calendar.DAY_OF_YEAR,1);
				scheduler.Generator.generate( new GregorianCalendar(), cal);
				cal = new GregorianCalendar();
				cal.setTime(((SpinnerDateModel)date.getModel()).getDate());
				panel.setMonth(cal.get(Calendar.YEAR),cal.get(Calendar.MONTH));
			}
		});
	}
}
